package drds.plus.executor.function.scalar.string;

import drds.plus.executor.ExecuteContext;
import drds.plus.executor.function.scalar.ScalarFunction;
import drds.plus.executor.utils.Utils;
import drds.plus.sql_process.type.Type;
import drds.tools.$;

/**
 * <pre>
 * ASCII(str)
 *
 * Returns the numeric value of the leftmost character of the string str. Returns 0 if str is the empty string. Returns NULL_KEY if str is NULL_KEY. ASCII() works for 8-bit characters.
 *
 * mysql> SELECT ASCII('2');
 *         -> 50
 * mysql> SELECT ASCII(2);
 *         -> 50
 * mysql> SELECT ASCII('dx');
 *         -> 100
 *
 * See also the ORD() function.
 * </pre>
 *
 * @author mengshi.sunmengshi 2014年4月11日 下午1:33:36
 * @since 5.1.0
 */
public class Ascii extends ScalarFunction {

    public Type getReturnType() {
        return Type.LongType;
    }

    public String[] getFunctionNames() {
        return new String[]{"ASCII"};
    }

    public Object compute(ExecuteContext executeContext, Object[] args) {
        Object arg = args[0];

        if (Utils.isNull(arg)) {
            return null;
        }

        String str = Type.StringType.convert(arg);
        if ($.isNullOrEmpty(str)) {
            return 0;
        }

        char leftMost = str.charAt(0);
        Type type = getReturnType();
        return type.convert(leftMost);
    }

}
